<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Promo extends Stourweb_Controller
{
    public function action_ad_list()
    {
        $action = $this->params['action'];
        if (empty($action)) {
            $this->display('admin/promo/ad_list');
        } elseif ($action == 'read') {
            $params = [
                'start'      => Arr::get($_GET, 'start'),
                'limit'      => Arr::get($_GET, 'limit', 20),
                'keyword'    => Arr::get($_GET, 'keyword'),
                'start_time' => Arr::get($_GET, 'start_time'),
                'end_time'   => Arr::get($_GET, 'end_time'),
                'type'       => Arr::get($_GET, 'type'),
                'status'     => Arr::get($_GET, 'status'),
            ];
            $res    = Model_Promo::promo_list($params);

            echo json_encode($res);
        } elseif ($action == 'delete') {
            $rawdata=file_get_contents('php://input');
            $data=json_decode($rawdata);
            $id=$data->id;
            if(is_numeric($id))
            {
                DB::delete('promo')->where('id','=',$id)->execute();
            }
        } elseif ($action == 'update') {
            $field = Arr::get($_POST, 'field');
            $id    = Arr::get($_POST, 'id');
            $value = Arr::get($_POST, 'val');
            if($id){
                $info      = DB::select()->from('promo')->where('id', '=', $id)->execute()->current();
                $page_link = json_decode($info['page_link'], true);
                $date      = strtotime(date('Ymd'));
                foreach ($page_link as $v) {
                    $page_link = str_replace('/','\\\\\\\\/',$v);//兼容mysql5.7以下，才这么写的
                    $is_exist = DB::select()->from('promo')
                        ->where(DB::expr("is_open=1 and page_link like '%{$page_link}%' and id!={$id} and end_date>{$date}"))
                        ->execute()->current();
//                    $is_exist = DB::select()->from('promo')
//                        ->where(DB::expr("is_open=1 and JSON_CONTAINS(page_link, '\"{$v}\"') and id!={$id} and end_date>{$date}"))
//                        ->execute()->current();
                    if ($is_exist) {
                        exit(json_encode([
                            'status' => false,
                            'msg'    => '您所选择的广告，配置的展示页面与开启的广告展示页重复，不可开启！'
                        ]));
                    }
                }
                DB::update('promo')->set([$field => $value])->where('id', '=', $id)->execute();
            }
            echo json_encode([
                'status' => true
            ]);
        }
    }

    public function action_add_promo()
    {
        $info = [
            'type'         => 1,
            'coupon_style' => 0,
            'frequency'    => 1,
            'page_type'    => 0,
        ];

        $this->assign('info',$info);
        $this->assign('min_date',date('Y-m-d'));
        $this->display('admin/promo/edit');
    }

    public function action_edit()
    {
        $id = $this->params['promo_id'];
        $info = Model_Promo::promo_detail($id);

        $this->assign('info',$info);
        $this->display('admin/promo/edit');
    }

    public function action_ajax_promo_save()
    {
        try {
            $promo_id = Arr::get($_POST, 'promo_id');
            $params   = [
                'title'      => Arr::get($_POST, 'title'),
                'start_date' => strtotime(Arr::get($_POST, 'start_date')),
                'end_date'   => strtotime(Arr::get($_POST, 'end_date')),
                'auto_time'  => Arr::get($_POST, 'auto_time',10),
                'frequency'  => Arr::get($_POST, 'frequency',1),
                'type'       => Arr::get($_POST, 'type'),
                'page_type'  => Arr::get($_POST, 'page_type'),
            ];
            if(empty($params['title'])){
                throw new Exception('请填写活动名称！');
            }
            if(empty($params['start_date']) || empty($params['end_date'])){
                throw new Exception('请填选择活动时间！');
            }
            switch ($params['type'])
            {
                case 1:
                case 2:
                    $img_url  = Arr::get($_POST, 'img_url');
                    $jump_url = Arr::get($_POST, 'jump_url');
                    if (count($img_url) != count($jump_url)) {
                        throw new Exception('广告图与跳转地址未对应！');
                    }
                    if (count($img_url) < 1) {
                        throw new Exception('请上传图片！');
                    }
                    if (count($img_url) > 10) {
                        throw new Exception('最多添加10个广告位！');
                    }
                    if (count($jump_url) < 1) {
                        throw new Exception('请设置跳转地址！');
                    }
                    $params['piclist'] = implode('||', $img_url) . ',' . implode('||', $jump_url);
                    break;
                case 3:
                    $coupon_id    = Arr::get($_POST, 'coupon_id');
                    $coupon_style = Arr::get($_POST, 'coupon_style');
                    $coupon_img   = Arr::get($_POST, 'coupon_img');
                    if (count($coupon_id) < 1) {
                        throw new Exception('请配置优惠券！');
                    }
                    if ($coupon_style == 1 && empty($coupon_img)) {
                        throw new Exception('请上传背景图！');
                    }
                    $params['coupon_id']    = implode(',', $coupon_id);
                    $params['coupon_style'] = $coupon_style;
                    $params['coupon_img']   = $coupon_img;
                    break;
                case 4:
                    $video = Arr::get($_POST, 'video');
                    if(empty($video)){
                        throw new Exception('请上传背视频！');
                    }
                    $params['video'] = $video;
            }
            if($params['page_type']==1){
                $page_link = Arr::get($_POST, 'page_link');
                if(count($page_link)<1){
                    throw new Exception('请选择展示的页面！');
                }
                $params['page_link'] = $page_link;
            }else{
                $params['page_link'] = ['/pages/index/home'];
            }
            $sql  = $promo_id?" and id!={$promo_id} ":'';
            $date = strtotime(date('Ymd'));
            foreach ($params['page_link'] as $v) {
                $page_link = str_replace('/','\\\\\\\\/',$v);
                $is_exist = DB::select()->from('promo')
                    ->where(DB::expr("is_open=1 and page_link like '%{$page_link}%' {$sql} and end_date>{$date}"))
                    ->execute()->current();
                if($is_exist){
                    throw new Exception('您设置的展示页面，已有其它广告占用，请停用后再进行添加！');
                }
            }
            $params['page_link'] = json_encode($params['page_link'],256);

            $res = Model_Promo::promo_handle($params, $promo_id);
        } catch (Exception $e) {
            $res = [
                'status' => false,
                'msg'    => $e->getMessage()
            ];
        }

        echo json_encode($res);
    }

    public function action_dialog_coupon_list()
    {
        $action = $this->params['action'];
        if(empty($action)){
            $coupon_id = Arr::get($_GET, 'coupon_id');

            $this->assign('coupon_id', $coupon_id);
            $this->display('admin/promo/dialog/coupon_list');
        }elseif($action=='read'){
            $params = [
                'start'     => Arr::get($_GET, 'start'),
                'limit'     => Arr::get($_GET, 'limit'),
                'keyword'   => Arr::get($_GET, 'keyword'),
                'coupon_id' => Arr::get($_GET, 'coupon_id'),
            ];
            $res = Model_Promo::get_coupon_list($params);

            echo json_encode($res);
        }
    }

    public function action_dialog_page_list()
    {
        $action = $this->params['action'];
        if (empty($action)) {
            $this->display('admin/promo/dialog/page_list');
        } elseif ($action == 'read') {
            $keyword   = Arr::get($_GET, 'keyword');
            $list      = Kohana::$config->load('uniapp')->get('nav');
            $page      = $list['model_page'];
            $page_list = [
                [
                    'name'    => '首页',
                    'type_id' => 0,
                    'path'    => '/pages/index/home',
                    'title'   => 'UNI端首页',
                ]
            ];
            foreach ($page as $v) {
                $type_name = '';
                if ($v['typeid']) {
                    $type_name = DB::select()->from('model')->where('id', '=', $v['typeid'])->execute()->get('modulename');
                }
                if ($type_name) {
                    if($keyword && mb_strpos($type_name, $keyword) === false){
                        continue;
                    }
                    $v['page'][0]['name'] = $type_name;
                    $v['page'][0]['type_id'] = $v['typeid'];

                    $page_list[] = $v['page'][0];
                    if (isset($v['page'][1]) && strpos($v['page'][1]['path'], 'detail') === false) {
                        $v['page'][1]['name'] = $type_name;
                        $v['page'][1]['type_id'] = $v['typeid'];
                        $page_list[] = $v['page'][1];
                    }
                }
            }
            $res = [
                'total'   => count($page_list),
                'lists'   => $page_list,
                'success' => true
            ];

            echo json_encode($res);
        }
    }

    public function action_pendant()
    {
        $config = [
            'cfg_promo_pendant_status' => '',
            'cfg_promo_pendant_img'    => '',
            'cfg_promo_pendant_link'   => '',
        ];
        foreach ($config as $k=>&$v) {
            $v = DB::select('value')->from('sysconfig')->where('varname', '=', $k)->execute()->get('value');
        }
        if($config['cfg_promo_pendant_link']){
            $link = json_decode(urldecode($config['cfg_promo_pendant_link']), true);
            $config['link'] = $link;
        }

        $this->assign('config', $config);
        $this->display('admin/promo/pendant');
    }

    public function action_ajax_pendant_save()
    {
        $params = [
            'cfg_promo_pendant_status' => Arr::get($_POST, 'cfg_promo_pendant_status'),
            'cfg_promo_pendant_img'    => Arr::get($_POST, 'cfg_promo_pendant_img'),
            'cfg_promo_pendant_link'   => Arr::get($_POST, 'cfg_promo_pendant_link'),
        ];
        foreach ($params as $k => $v) {
            $is_exist = DB::select()->from('sysconfig')->where('varname', '=', $k)->execute()->current();
            if ($is_exist) {
                DB::update('sysconfig')->set(array('value' => $v))->where('varname', '=', $k)->execute();
            } else {
                $data = [
                    'webid'   => 0,
                    'varname' => $k,
                    'value'   => $v
                ];
                DB::insert('sysconfig')->columns(array_keys($data))->values(array_values($data))->execute();
            }
        }

        echo json_encode([
            'status' => true
        ]);
    }
}